#!/bin/bash

# 安全移除硬盘脚本
# 功能：安全地移除USB/SATA/NVMe硬盘，避免数据损坏

# 重试函数
retry_command() {
    local cmd="$1"
    local max_attempts=${2:-3}
    local delay=${3:-2}
    
    for ((i=1; i<=max_attempts; i++)); do
        if eval "$cmd"; then
            return 0
        fi
        if [[ $i -lt $max_attempts ]]; then
            echo "  尝试 $i/$max_attempts 失败，${delay}秒后重试..."
            sleep $delay
        fi
    done
    return 1
}

# 列出磁盘，排除系统盘和虚拟内存只读盘引导盘等等和系统相关的盘
echo "🔍 扫描系统中的磁盘..."

# 获取系统盘和关键盘（根目录、引导、交换分区等）
SYSTEM_DISKS=$(lsblk -n -o NAME,MOUNTPOINT 2>/dev/null | awk '$2 ~ /^\/($|boot|efi|var|usr|home$)/ || $2 ~ /^\/.*/ {print $1}' | sed 's/[0-9]*$//' | sort -u)
SWAP_DISKS=$(swapon --show=NAME --noheadings 2>/dev/null | xargs -r -n1 basename 2>/dev/null | sed 's/[0-9]*$//' | sort -u)

# 合并所有系统相关磁盘
ALL_SYSTEM_DISKS=$(echo -e "$SYSTEM_DISKS\n$SWAP_DISKS" | sort -u)

echo "📋 可安全移除的磁盘列表（已排除系统盘）："
echo "----------------------------------------"

# 显示可移除磁盘列表
AVAILABLE_DISKS=()
while IFS= read -r disk; do
    if [[ -n "$disk" && ! " ${ALL_SYSTEM_DISKS[@]} " =~ " ${disk} " ]]; then
        # 获取磁盘信息
        MODEL=$(lsblk -d -o NAME,MODEL,SIZE 2>/dev/null | grep "^$disk" | awk '{$1=""; print $0}' | sed 's/^ *//')
        if [[ -n "$MODEL" ]]; then
            echo "  ${disk}: $MODEL"
            AVAILABLE_DISKS+=("$disk")
        fi
    fi
done < <(lsblk -nd -o NAME 2>/dev/null | grep -E '^[a-z]+$')

if [[ ${#AVAILABLE_DISKS[@]} -eq 0 ]]; then
    echo "❌ 未找到可安全移除的磁盘"
    exit 1
fi

echo "----------------------------------------"

# 用户输入设备名，例如sda即可
while true; do
    read -p "请输入要移除的磁盘设备名（如sdb）: " USER_INPUT
    USER_INPUT=$(echo "$USER_INPUT" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]//g')

    # 检查输入是否为合理
    if [[ -z "$USER_INPUT" ]]; then
        echo "❌ 输入为空，请重新输入有效的磁盘设备名"
        continue
    fi

    # 验证输入格式（应该是sda、sdb、nvme0n1等格式）
    if ! [[ "$USER_INPUT" =~ ^[a-z]+[0-9]*[a-z]*[0-9]*$ ]]; then
        echo "❌ 输入格式错误，请输入有效的磁盘设备名（如sdb、nvme0n1）"
        continue
    fi

    # 提取设备短名（去掉数字部分）
    if [[ "$USER_INPUT" =~ ^(nvme[0-9]+n[0-9]+) ]]; then
        DEVICE_SHORT="${BASH_REMATCH[1]}"
        DEVICE="/dev/${USER_INPUT}"
    else
        DEVICE_SHORT=$(echo "$USER_INPUT" | sed 's/[0-9]*$//')
        DEVICE="/dev/${USER_INPUT}"
    fi

    # 检查设备是否存在
    if [[ ! -b "$DEVICE" && ! -b "/dev/${DEVICE_SHORT}" ]]; then
        echo "❌ 设备 $DEVICE 不存在，请检查输入"
        continue
    fi

    # 检查是否为系统盘虚拟内存只读盘引导盘等等和系统相关的盘
    if [[ " ${ALL_SYSTEM_DISKS[@]} " =~ " ${DEVICE_SHORT} " ]]; then
        echo "❌ 严重警告：$DEVICE 是系统关键磁盘，禁止移除！"
        echo "   这可能导致系统崩溃或无法启动"
        continue
    fi

    # 检查设备是否在可用磁盘列表中
    if ! [[ " ${AVAILABLE_DISKS[@]} " =~ " ${DEVICE_SHORT} " ]]; then
        echo "⚠️  警告：$DEVICE 不在可安全移除的磁盘列表中"
        while true; do
            read -p "是否继续？(y/N): " -r
            if [[ $REPLY =~ ^[Yy]$ ]]; then
                break 2  # 跳出两层循环
            elif [[ $REPLY =~ ^[Nn]$ || -z "$REPLY" ]]; then
                echo "请重新输入设备名"
                break
            else
                echo "❌ 无效输入，请输入 y 或 n"
            fi
        done
    else
        break  # 输入有效，退出循环
    fi
done

echo ""
echo "✅ 已选择设备: $DEVICE"

# 列出文件占用和进程占用（详细显示）
echo "🔎 检查磁盘占用情况..."
OCCUPIED=false
PROCESS_FOUND=false

echo ""
echo "📌 分区挂载检查:"
echo "========================"

# 检查1分区挂载情况
MOUNTED_PARTS=()
HAS_MOUNTED=false

for part in ${DEVICE}[0-9]* ${DEVICE}-* ${DEVICE}p[0-9]*; do
    if [ -b "$part" ]; then
        if mountpoint -q "$part" 2>/dev/null || mount | grep -q "$part"; then
            MOUNT_INFO=$(mount | grep "$part")
            MOUNT_POINT=$(echo "$MOUNT_INFO" | awk '{print $3}')
            FS_TYPE=$(echo "$MOUNT_INFO" | awk '{print $5}')
            echo "✅ 分区 $part 挂载在: $MOUNT_POINT (文件系统: $FS_TYPE)"
            MOUNTED_PARTS+=("$part:$MOUNT_POINT")
            HAS_MOUNTED=true
            
            # 显示挂载点的磁盘使用情况
            if df -h | grep -q "$part"; then
                USAGE_INFO=$(df -h | grep "$part" | awk '{print "  使用情况: " $5 " (" $3 "/" $2 ")"}')
                echo "$USAGE_INFO"
            fi
            echo ""
        fi
    fi
done

if [[ "$HAS_MOUNTED" == "false" ]]; then
    echo "❌ 没有发现挂载的分区"
    echo ""
fi

echo "🔍 进程占用检查:"
echo "========================"

# 检查2设备本身的进程占用
if command -v lsof >/dev/null 2>&1; then
    echo ""
    echo "📌 检查设备级进程占用:"
    echo "------------------------"
    DEVICE_PROCESSES=$(sudo lsof "$DEVICE" 2>/dev/null | grep -v "^COMMAND" || true)
    if [[ -n "$DEVICE_PROCESSES" ]]; then
        echo "⚠️  设备 $DEVICE 被以下进程占用:"
        echo "$DEVICE_PROCESSES" | head -20 | while read line; do
            PROCESS_NAME=$(echo "$line" | awk '{print $1}')
            PROCESS_PID=$(echo "$line" | awk '{print $2}')
            # 识别系统关键进程 - 改进的匹配逻辑
            IS_SYSTEM_PROCESS=false
            
            # 精确匹配常见系统进程
            if [[ "$PROCESS_NAME" =~ ^(mysql|mariadb|postgres|nginx|apache|httpd|docker|containerd|kube|udevadm|hdparm|smartd|smartctl|trim|systemd|systemd-journal|systemd-udevd|systemd-logind|systemd-networkd|systemd-resolved)$ ]]; then
                IS_SYSTEM_PROCESS=true
            fi
            
            # 部分匹配系统进程（处理截断的进程名）
            if [[ "$PROCESS_NAME" =~ ^systemd- ]] || 
               [[ "$PROCESS_NAME" =~ ^udev ]] || 
               [[ "$PROCESS_NAME" =~ ^smart ]] || 
               [[ "$PROCESS_NAME" =~ ^hdparm ]] ||
               [[ "$PROCESS_NAME" =~ ^docker ]] ||
               [[ "$PROCESS_NAME" =~ ^containerd ]] ||
               [[ "$PROCESS_NAME" =~ ^kube ]]; then
                IS_SYSTEM_PROCESS=true
            fi
            
            # 包含关键词匹配
            if [[ "$PROCESS_NAME" =~ (db|sql|web|server|docker|container|udev|hdparm|smart|trim|system) ]]; then
                IS_SYSTEM_PROCESS=true
            fi
            
            if [[ "$IS_SYSTEM_PROCESS" == "true" ]]; then
                echo "  🚨 $line (系统关键进程)"
            else
                echo "  📄 $line"
            fi
        done
        if [[ $(echo "$DEVICE_PROCESSES" | wc -l) -gt 20 ]]; then
            echo "    ... 还有更多进程，共 $(echo "$DEVICE_PROCESSES" | wc -l) 个进程"
        fi
        PROCESS_FOUND=true
        OCCUPIED=true
    else
        echo "✅ 设备 $DEVICE 无进程占用"
    fi
else
    echo "❌ lsof 命令不可用，无法检查进程占用"
fi

# 检查3所有分区的进程占用
if command -v lsof >/dev/null 2>&1; then
    echo ""
    echo "📌 检查分区级进程占用:"
    echo "------------------------"
    PART_PROCESS_FOUND=false
    for part in ${DEVICE}[0-9]* ${DEVICE}-* ${DEVICE}p[0-9]*; do
        if [ -b "$part" ]; then
            PART_PROCESSES=$(sudo lsof "$part" 2>/dev/null | grep -v "^COMMAND" || true)
            if [[ -n "$PART_PROCESSES" ]]; then
                echo "⚠️  分区 $part 被以下进程占用:"
                echo "$PART_PROCESSES" | head -15 | while read line; do
                    PROCESS_NAME=$(echo "$line" | awk '{print $1}')
                    PROCESS_PID=$(echo "$line" | awk '{print $2}')
                    # 识别系统关键进程 - 改进的匹配逻辑
                    IS_SYSTEM_PROCESS=false
                    
                    # 精确匹配常见系统进程
                    if [[ "$PROCESS_NAME" =~ ^(mysql|mariadb|postgres|nginx|apache|httpd|docker|containerd|kube|udevadm|hdparm|smartd|smartctl|trim|systemd|systemd-journal|systemd-udevd|systemd-logind|systemd-networkd|systemd-resolved)$ ]]; then
                        IS_SYSTEM_PROCESS=true
                    fi
                    
                    # 部分匹配系统进程（处理截断的进程名）
                    if [[ "$PROCESS_NAME" =~ ^systemd- ]] || 
                       [[ "$PROCESS_NAME" =~ ^udev ]] || 
                       [[ "$PROCESS_NAME" =~ ^smart ]] || 
                       [[ "$PROCESS_NAME" =~ ^hdparm ]] ||
                       [[ "$PROCESS_NAME" =~ ^docker ]] ||
                       [[ "$PROCESS_NAME" =~ ^containerd ]] ||
                       [[ "$PROCESS_NAME" =~ ^kube ]]; then
                        IS_SYSTEM_PROCESS=true
                    fi
                    
                    # 包含关键词匹配
                    if [[ "$PROCESS_NAME" =~ (db|sql|web|server|docker|container|udev|hdparm|smart|trim|system) ]]; then
                        IS_SYSTEM_PROCESS=true
                    fi
                    
                    if [[ "$IS_SYSTEM_PROCESS" == "true" ]]; then
                        echo "    🚨 $line (系统关键进程)"
                    else
                        echo "    📄 $line"
                    fi
                done
                if [[ $(echo "$PART_PROCESSES" | wc -l) -gt 15 ]]; then
                    echo "    ... 还有更多进程，共 $(echo "$PART_PROCESSES" | wc -l) 个进程"
                fi
                PROCESS_FOUND=true
                OCCUPIED=true
                PART_PROCESS_FOUND=true
                echo ""
            fi
        fi
    done
    if [[ "$PART_PROCESS_FOUND" == "false" ]]; then
        echo "✅ 所有分区均无进程占用"
    fi
fi

# 检查4挂载点的进程占用
if [[ ${#MOUNTED_PARTS[@]} -gt 0 ]] && command -v lsof >/dev/null 2>&1; then
    echo ""
    echo "📌 检查挂载点进程占用:"
    echo "------------------------"
    MOUNT_PROCESS_FOUND=false
    for part_mount in "${MOUNTED_PARTS[@]}"; do
        MOUNT_POINT="${part_mount#*:}"
        
        MOUNT_PROCESSES=$(sudo lsof +D "$MOUNT_POINT" 2>/dev/null | grep -v "^COMMAND" || true)
        if [[ -n "$MOUNT_PROCESSES" ]]; then
            echo "⚠️  挂载点 $MOUNT_POINT 被以下进程占用:"
            echo "$MOUNT_PROCESSES" | head -10 | while read line; do
                PROCESS_NAME=$(echo "$line" | awk '{print $1}')
                PROCESS_PID=$(echo "$line" | awk '{print $2}')
                # 识别系统关键进程 - 改进的匹配逻辑
                IS_SYSTEM_PROCESS=false
                
                # 精确匹配常见系统进程
                if [[ "$PROCESS_NAME" =~ ^(mysql|mariadb|postgres|nginx|apache|httpd|docker|containerd|kube|udevadm|hdparm|smartd|smartctl|trim|systemd|systemd-journal|systemd-udevd|systemd-logind|systemd-networkd|systemd-resolved)$ ]]; then
                    IS_SYSTEM_PROCESS=true
                fi
                
                # 部分匹配系统进程（处理截断的进程名）
                if [[ "$PROCESS_NAME" =~ ^systemd- ]] || 
                   [[ "$PROCESS_NAME" =~ ^udev ]] || 
                   [[ "$PROCESS_NAME" =~ ^smart ]] || 
                   [[ "$PROCESS_NAME" =~ ^hdparm ]] ||
                   [[ "$PROCESS_NAME" =~ ^docker ]] ||
                   [[ "$PROCESS_NAME" =~ ^containerd ]] ||
                   [[ "$PROCESS_NAME" =~ ^kube ]]; then
                    IS_SYSTEM_PROCESS=true
                fi
                
                # 包含关键词匹配
                if [[ "$PROCESS_NAME" =~ (db|sql|web|server|docker|container|udev|hdparm|smart|trim|system) ]]; then
                    IS_SYSTEM_PROCESS=true
                fi
                
                if [[ "$IS_SYSTEM_PROCESS" == "true" ]]; then
                    echo "    🚨 $line (系统关键进程)"
                else
                    echo "    📄 $line"
                fi
            done
            if [[ $(echo "$MOUNT_PROCESSES" | wc -l) -gt 10 ]]; then
                echo "    ... 还有更多进程，共 $(echo "$MOUNT_PROCESSES" | wc -l) 个进程"
            fi
            PROCESS_FOUND=true
            OCCUPIED=true
            MOUNT_PROCESS_FOUND=true
            echo ""
        fi
    done
    if [[ "$MOUNT_PROCESS_FOUND" == "false" ]]; then
        echo "✅ 所有挂载点均无进程占用"
    fi
fi

# 检查5使用fuser作为备用检查方法
if command -v fuser >/dev/null 2>&1; then
    echo ""
    echo "📌 使用fuser检查文件占用:"
    echo "------------------------"
    FUSER_FOUND=false
    for part_mount in "${MOUNTED_PARTS[@]}"; do
        MOUNT_POINT="${part_mount#*:}"
        FUSER_PROCESSES=$(sudo fuser -v "$MOUNT_POINT" 2>/dev/null || true)
        if [[ -n "$FUSER_PROCESSES" ]]; then
            echo "⚠️  fuser检查挂载点 $MOUNT_POINT:"
            echo "$FUSER_PROCESSES" | while read line; do
                echo "  🔧 $line"
            done
            PROCESS_FOUND=true
            OCCUPIED=true
            FUSER_FOUND=true
            echo ""
        fi
    done
    if [[ "$FUSER_FOUND" == "false" ]]; then
        echo "✅ fuser检查无进程占用"
    fi
fi

echo "========================"
echo ""

# 总结占用情况 - 只考虑进程占用，不考虑挂载点
if [[ "$OCCUPIED" == "true" ]]; then
    echo "⚠️  ⚠️  ⚠️  警告：发现进程占用 ⚠️  ⚠️  ⚠️"
    echo "========================================"
    
    # 显示具体的占用类型和详细信息
    if [[ "$PROCESS_FOUND" == "true" ]]; then
        echo "📌 进程占用汇总:"
        echo ""
        
        # 重新显示设备级进程占用
        if [[ -n "$DEVICE_PROCESSES" ]]; then
            echo "🔧 设备级占用:"
            echo "$DEVICE_PROCESSES" | head -5 | while read line; do
                PROCESS_NAME=$(echo "$line" | awk '{print $1}')
                PROCESS_PID=$(echo "$line" | awk '{print $2}')
                # 识别系统关键进程 - 改进的匹配逻辑
                IS_SYSTEM_PROCESS=false
                
                # 精确匹配常见系统进程
                if [[ "$PROCESS_NAME" =~ ^(mysql|mariadb|postgres|nginx|apache|httpd|docker|containerd|kube|udevadm|hdparm|smartd|smartctl|trim|systemd|systemd-journal|systemd-udevd|systemd-logind|systemd-networkd|systemd-resolved)$ ]]; then
                    IS_SYSTEM_PROCESS=true
                fi
                
                # 部分匹配系统进程（处理截断的进程名）
                if [[ "$PROCESS_NAME" =~ ^systemd- ]] || 
                   [[ "$PROCESS_NAME" =~ ^udev ]] || 
                   [[ "$PROCESS_NAME" =~ ^smart ]] || 
                   [[ "$PROCESS_NAME" =~ ^hdparm ]] ||
                   [[ "$PROCESS_NAME" =~ ^docker ]] ||
                   [[ "$PROCESS_NAME" =~ ^containerd ]] ||
                   [[ "$PROCESS_NAME" =~ ^kube ]]; then
                    IS_SYSTEM_PROCESS=true
                fi
                
                # 包含关键词匹配
                if [[ "$PROCESS_NAME" =~ (db|sql|web|server|docker|container|udev|hdparm|smart|trim|system) ]]; then
                    IS_SYSTEM_PROCESS=true
                fi
                
                if [[ "$IS_SYSTEM_PROCESS" == "true" ]]; then
                    echo "    🚨 $line (系统进程)"
                else
                    echo "    📄 $line"
                fi
            done
            if [[ $(echo "$DEVICE_PROCESSES" | wc -l) -gt 5 ]]; then
                echo "    ... 还有更多进程，共 $(echo "$DEVICE_PROCESSES" | wc -l) 个进程"
            fi
            echo ""
        fi
        
        # 重新显示分区级进程占用
        PART_PROCESS_FOUND=false
        for part in ${DEVICE}[0-9]* ${DEVICE}-* ${DEVICE}p[0-9]*; do
            if [ -b "$part" ]; then
                PART_PROCESSES=$(sudo lsof "$part" 2>/dev/null | grep -v "^COMMAND" || true)
                if [[ -n "$PART_PROCESSES" ]]; then
                    PART_PROCESS_FOUND=true
                    echo "🔧 分区 $part 占用:"
                    echo "$PART_PROCESSES" | head -3 | while read line; do
                        PROCESS_NAME=$(echo "$line" | awk '{print $1}')
                        PROCESS_PID=$(echo "$line" | awk '{print $2}')
                        # 识别系统关键进程 - 改进的匹配逻辑
                        IS_SYSTEM_PROCESS=false
                        
                        # 精确匹配常见系统进程
                        if [[ "$PROCESS_NAME" =~ ^(mysql|mariadb|postgres|nginx|apache|httpd|docker|containerd|kube|udevadm|hdparm|smartd|smartctl|trim|systemd|systemd-journal|systemd-udevd|systemd-logind|systemd-networkd|systemd-resolved)$ ]]; then
                            IS_SYSTEM_PROCESS=true
                        fi
                        
                        # 部分匹配系统进程（处理截断的进程名）
                        if [[ "$PROCESS_NAME" =~ ^systemd- ]] || 
                           [[ "$PROCESS_NAME" =~ ^udev ]] || 
                           [[ "$PROCESS_NAME" =~ ^smart ]] || 
                           [[ "$PROCESS_NAME" =~ ^hdparm ]] ||
                           [[ "$PROCESS_NAME" =~ ^docker ]] ||
                           [[ "$PROCESS_NAME" =~ ^containerd ]] ||
                           [[ "$PROCESS_NAME" =~ ^kube ]]; then
                            IS_SYSTEM_PROCESS=true
                        fi
                        
                        # 包含关键词匹配
                        if [[ "$PROCESS_NAME" =~ (db|sql|web|server|docker|container|udev|hdparm|smart|trim|system) ]]; then
                            IS_SYSTEM_PROCESS=true
                        fi
                        
                        if [[ "$IS_SYSTEM_PROCESS" == "true" ]]; then
                            echo "    🚨 $line (系统进程)"
                        else
                            echo "    📄 $line"
                        fi
                    done
                    if [[ $(echo "$PART_PROCESSES" | wc -l) -gt 3 ]]; then
                        echo "    ... 还有更多进程，共 $(echo "$PART_PROCESSES" | wc -l) 个进程"
                    fi
                    echo ""
                fi
            fi
        done
        
        # 重新显示挂载点进程占用
        if [[ ${#MOUNTED_PARTS[@]} -gt 0 ]]; then
            MOUNT_PROCESS_FOUND=false
            for part_mount in "${MOUNTED_PARTS[@]}"; do
                MOUNT_POINT="${part_mount#*:}"
                MOUNT_PROCESSES=$(sudo lsof +D "$MOUNT_POINT" 2>/dev/null | grep -v "^COMMAND" || true)
                if [[ -n "$MOUNT_PROCESSES" ]]; then
                    MOUNT_PROCESS_FOUND=true
                    echo "🔧 挂载点 $MOUNT_POINT 占用:"
                    echo "$MOUNT_PROCESSES" | head -3 | while read line; do
                        PROCESS_NAME=$(echo "$line" | awk '{print $1}')
                        PROCESS_PID=$(echo "$line" | awk '{print $2}')
                        # 识别系统关键进程 - 改进的匹配逻辑
                        IS_SYSTEM_PROCESS=false
                        
                        # 精确匹配常见系统进程
                        if [[ "$PROCESS_NAME" =~ ^(mysql|mariadb|postgres|nginx|apache|httpd|docker|containerd|kube|udevadm|hdparm|smartd|smartctl|trim|systemd|systemd-journal|systemd-udevd|systemd-logind|systemd-networkd|systemd-resolved)$ ]]; then
                            IS_SYSTEM_PROCESS=true
                        fi
                        
                        # 部分匹配系统进程（处理截断的进程名）
                        if [[ "$PROCESS_NAME" =~ ^systemd- ]] || 
                           [[ "$PROCESS_NAME" =~ ^udev ]] || 
                           [[ "$PROCESS_NAME" =~ ^smart ]] || 
                           [[ "$PROCESS_NAME" =~ ^hdparm ]] ||
                           [[ "$PROCESS_NAME" =~ ^docker ]] ||
                           [[ "$PROCESS_NAME" =~ ^containerd ]] ||
                           [[ "$PROCESS_NAME" =~ ^kube ]]; then
                            IS_SYSTEM_PROCESS=true
                        fi
                        
                        # 包含关键词匹配
                        if [[ "$PROCESS_NAME" =~ (db|sql|web|server|docker|container|udev|hdparm|smart|trim|system) ]]; then
                            IS_SYSTEM_PROCESS=true
                        fi
                        
                        if [[ "$IS_SYSTEM_PROCESS" == "true" ]]; then
                            echo "    🚨 $line (系统进程)"
                        else
                            echo "    📄 $line"
                        fi
                    done
                    if [[ $(echo "$MOUNT_PROCESSES" | wc -l) -gt 3 ]]; then
                        echo "    ... 还有更多进程，共 $(echo "$MOUNT_PROCESSES" | wc -l) 个进程"
                    fi
                    echo ""
                fi
            done
        fi
        
        # 如果没有找到具体的进程信息，显示通用提示
        if [[ -z "$DEVICE_PROCESSES" && "$PART_PROCESS_FOUND" == "false" && "$MOUNT_PROCESS_FOUND" == "false" ]]; then
            echo "⚠️  发现进程占用，但无法获取详细进程信息"
            echo ""
        fi
    fi
    
    # 提示脚本不执行杀进程，避免产生其他问题。
    echo "⚠️  注意：本脚本不杀进程，以免误杀系统进程或产生其他问题！！！请按以前检查结果手动处理。例如结束相册、影音，docker、下载等应用，结束smb共享等等再尝试，强制移除有风险！！！"
    echo ""
    
    # 提供选项
    while true; do
        echo "请选择操作："
        echo "y) ⚠️  强制移除（⚠️  有数据丢失风险！）"
        echo "n) 退出脚本，手动解除文件占用后重新运行"
        echo ""
        
        read -p "请输入选择 (y 或 n): " -r
        case $REPLY in
            y|Y)
                # 二次确认
                echo ""
                echo "⚠️  您选择了跳过进程检查，这可能导致数据丢失！"
                read -p "请输入 'yes' 确认继续移除: " CONFIRM
                if [[ "${CONFIRM,,}" == "yes" ]]; then
                    echo "⏭️  忽略进程，进入强制移除流程..."
                    break
                else
                    echo "❌ 确认失败，返回选择菜单"
                    echo ""
                fi
                ;;
            n|N)
                echo "👋 退出脚本，请手动处理占用后重新运行"
                exit 0
                ;;
            *)
                echo "❌ 无效选择，请重新输入 y 或 n"
                ;;
        esac
    done
else
    echo "✅ 未发现进程占用，可以安全继续"
fi


echo ""
echo "========================================"
echo "          开始移除流程"
echo "========================================"

# 开始安全移除硬盘的主流程
echo -e "\n🚀 开始移除硬盘 $DEVICE..."

# 0. 最终确认
while true; do
    read -p "确认要移除设备 $DEVICE？这将卸载所有分区并从系统移除设备 (y/N): " -r
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        break
    elif [[ $REPLY =~ ^[Nn]$ || -z "$REPLY" ]]; then
        echo "操作已取消"
        exit 0
    else
        echo "❌ 无效输入，请输入 y 或 n"
    fi
done

# 1. 刷新磁盘缓存
echo "🔄 刷新磁盘缓存..."
retry_command "sudo blockdev --flushbufs $DEVICE 2>/dev/null" 2 1

sleep 2

# 刷新所有分区缓存
for part in ${DEVICE}[0-9]* ${DEVICE}-* ${DEVICE}p[0-9]*; do
    if [ -b "$part" ]; then
        sudo blockdev --flushbufs "$part" 2>/dev/null
    fi
done

sleep 5

# 2. 同步数据
echo "📝 同步数据..."
sync

sleep 10

# 3. 检查并卸载所有分区（增强版）
echo "🔓 正在检查并卸载 $DEVICE 的所有分区..."

# 首先尝试正常卸载
for part in ${DEVICE}[0-9]* ${DEVICE}-* ${DEVICE}p[0-9]*; do
    if [ -b "$part" ] && (mountpoint -q "$part" 2>/dev/null || mount | grep -q "$part"); then
        echo "  正在卸载 $part..."
        if sudo umount "$part" 2>/dev/null; then
            echo "    ✅ 正常卸载成功"
        else
            echo "    ⚠️  正常卸载失败"
            # 显示阻止卸载的进程
            if command -v lsof >/dev/null 2>&1; then
                BLOCKING_PROCESSES=$(sudo lsof +f -- "$part" 2>/dev/null | head -5)
                if [[ -n "$BLOCKING_PROCESSES" ]]; then
                    echo "    🔍 阻止卸载的进程:"
                    echo "$BLOCKING_PROCESSES" | while read line; do
                        echo "      $line"
                    done
                fi
            fi
        fi
    fi
done

# 等待并检查是否有残留挂载
sleep 3
MOUNT_REMAINING=false

for part in ${DEVICE}[0-9]* ${DEVICE}-* ${DEVICE}p[0-9]*; do
    if [ -b "$part" ] && (mountpoint -q "$part" 2>/dev/null || mount | grep -q "$part"); then
        MOUNT_REMAINING=true
        MOUNT_POINT=$(mount | grep "$part" | awk '{print $3}')
        echo "  ⚠️  $part 仍在挂载点 $MOUNT_POINT，尝试强制卸载..."
        
        # 先尝试懒惰卸载
        if sudo umount -l "$part" 2>/dev/null; then
            echo "    ✅ 懒惰卸载成功"
        else
            echo "    ⚠️  懒惰卸载失败"
        fi
    fi
done

# 最终检查
MOUNT_FINAL_CHECK=false
for part in ${DEVICE}[0-9]* ${DEVICE}-* ${DEVICE}p[0-9]*; do
    if [ -b "$part" ] && (mountpoint -q "$part" 2>/dev/null || mount | grep -q "$part"); then
        MOUNT_FINAL_CHECK=true
        break
    fi
done

if [[ "$MOUNT_FINAL_CHECK" == "true" ]]; then
    echo "❌ 无法完全卸载所有分区，请手动处理"
    exit 1
else
    echo "✅ 所有分区已成功卸载"
fi

# 4. 执行设备移除（增强版）
echo "🔌 尝试移除设备..."
REMOVED=false

# 方法1: 内核接口移除 (适用于SATA/SAS)
if [[ -e "/sys/block/$DEVICE_SHORT/device/delete" ]]; then
    if sudo bash -c "echo 1 > /sys/block/$DEVICE_SHORT/device/delete" 2>/dev/null; then
        echo "✅ 通过内核接口移除成功"
        REMOVED=true
    fi
fi

# 方法2: NVMe专用移除
if [[ "$REMOVED" != "true" && "$DEVICE_SHORT" =~ ^nvme ]]; then
    if [[ -e "/sys/block/$DEVICE_SHORT/device/remove" ]]; then
        if sudo bash -c "echo 1 > /sys/block/$DEVICE_SHORT/device/remove" 2>/dev/null; then
            echo "✅ 通过NVMe接口移除成功"
            REMOVED=true
        fi
    fi
fi

# 方法3: SCSI通用移除
if [[ "$REMOVED" != "true" ]]; then
    if sudo eject -s "$DEVICE" 2>/dev/null; then
        echo "✅ 通过SCSI弹出指令移除成功"
        REMOVED=true
    fi
fi


# 方法4: USB设备移除
if [[ "$REMOVED" != "true" ]]; then
    USB_INFO=$(readlink "/sys/block/$DEVICE_SHORT" 2>/dev/null | grep -o 'usb[0-9]*' || true)
    if [[ -n "$USB_INFO" ]]; then
        if sudo udisksctl power-off -b "$DEVICE" 2>/dev/null; then
            echo "✅ 通过udisksctl移除USB设备成功"
            REMOVED=true
        elif command -v usb_modeswitch >/dev/null; then
            # 尝试USB模式切换作为最后手段
            VENDOR=$(udevadm info --query=property --name="$DEVICE" 2>/dev/null | grep ID_VENDOR_ID | cut -d= -f2)
            PRODUCT=$(udevadm info --query=property --name="$DEVICE" 2>/dev/null | grep ID_MODEL_ID | cut -d= -f2)
            if [[ -n "$VENDOR" && -n "$PRODUCT" ]]; then
                sudo usb_modeswitch -v "0x$VENDOR" -p "0x$PRODUCT" -b 2 -d 2>/dev/null
                echo "⚠️  已尝试USB模式切换，请等待几秒后检查设备状态"
                REMOVED=true
            fi
        fi
    fi
fi


# 方法5: 最后的尝试 - 设备重置
if [[ "$REMOVED" != "true" ]]; then
    echo "⚠️  标准方法失败，尝试设备重置..."
    if [[ -e "/sys/block/$DEVICE_SHORT/device/reset" ]]; then
        if sudo bash -c "echo 1 > /sys/block/$DEVICE_SHORT/device/reset" 2>/dev/null; then
            echo "✅ 通过设备重置移除成功"
            REMOVED=true
        fi
    fi
fi

if [[ "$REMOVED" != "true" ]]; then
    echo "❌ 所有移除方法失败"
    echo "💡 建议手动检查:"
    echo "   - 运行 'lsblk' 查看设备状态"
    echo "   - 运行 'dmesg | tail' 查看内核消息"
    echo "   - 尝试物理断开设备（有风险）"
    exit 1
fi

# 5. 验证移除结果（增强版）
echo "🔎 验证移除结果..."
sleep 2  # 给系统一些时间更新状态

# 多重验证方法
DEVICE_REMOVED=false

# 方法1: 检查lsblk
if ! lsblk | grep -q "$DEVICE_SHORT"; then
    echo "✅ lsblk验证: 设备已消失"
    DEVICE_REMOVED=true
else
    echo "⚠️  lsblk验证: 设备仍存在"
fi

# 方法2: 检查/sys/block
if [[ ! -d "/sys/block/$DEVICE_SHORT" ]]; then
    echo "✅ sysfs验证: 设备目录已消失"
    DEVICE_REMOVED=true
else
    echo "⚠️  sysfs验证: 设备目录仍存在"
fi

# 方法3: 检查/proc/partitions
if ! grep -q "$DEVICE_SHORT" /proc/partitions 2>/dev/null; then
    echo "✅ 分区表验证: 设备已移除"
    DEVICE_REMOVED=true
else
    echo "⚠️  分区表验证: 设备仍存在"
fi

if [[ "$DEVICE_REMOVED" == "true" ]]; then
    echo "🎉 设备已从系统完全移除"
    echo "💡 可以安全物理拔出"
else
    echo "⚠️  设备可能仍在系统中"
    echo "🔍 详细占用检查:"
    
    # 检查进程占用
    if command -v lsof >/dev/null 2>&1; then
        PROCESSES=$(sudo lsof +f -- "$DEVICE" 2>/dev/null)
        if [[ -n "$PROCESSES" ]]; then
            echo "📊 进程占用:"
            echo "$PROCESSES" | head -10 | while read line; do
                echo "  $line"
            done
        else
            echo "✅ 无进程占用"
        fi
    fi
    
    # 检查内核模块占用
    if lsmod | grep -q "$DEVICE_SHORT"; then
        echo "⚠️  可能有内核模块占用"
    fi
    
    echo "💡 建议:"
    echo "   - 等待几秒后重试验证"
    echo "   - 检查 dmesg 查看内核消息"
    echo "   - 尝试重启系统后移除"
fi

echo ""
echo "========================================"
echo "          脚本执行完成"
echo "========================================"